<template>
    <view>
        <view style="padding: 40rpx;background-color: #fff;">
            <view style="display: flex;justify-content: space-between;margin-bottom: 50rpx;">
                <text style="width: 50%;">题型（题数）</text>
                <text style="width: 20%;">题数</text>
                <text style="width: 20%;">分值</text>
            </view>
            <view v-for="(item, index) in questionTypes" :key="index" class="question-type">
                <text> {{ onChangeDict(item.type,
                    mapDictCodesData.allQuestionType) }} （{{ item.itemNum }}）</text>
                <u--input v-model="item.cnt" placeholder="数量" type="number"
                    :customStyle="{ width: '20%', marginRight: '30rpx' }" :max="item.itemNum" />
                <u--input v-model="item.score" placeholder="分值" type="number" :customStyle="{ width: '20%', }"
                    :max="item.itemNum" />
            </view>
            <view style="display: flex;justify-content: space-around;margin-top: 60rpx;">
                <view>总题：<text style="color: #37B874;">{{ totalNum }}</text>&nbsp;题</view>
                <view>共计：<text style="color: #37B874;">{{ totalScore }}</text>&nbsp;分</view>
            </view>
        </view>
        <view style="width: 100%;height: 40rpx;background-color: #f5f5f5;">

        </view>
        <view style="padding: 40rpx; background-color: #fff;margin-top: 30rpx;">
            <view v-for="(item, index) in fieldArr" style="position: relative;">
                <view style="display: flex;justify-content: space-between;align-items: center;margin-bottom: 40rpx;">
                    <view style="width: 70%;">
                        {{ item.text }}
                        <text v-if="item.vip" style="margin-left: 10rpx;background-color: #EED682;color: #A86C12;padding: 0 20rpx;border-radius: 15px;font-size: 12px;">vip1</text>    
                    </view>
                    <view v-if="item.type === 'switch'" style="width: 15%;">
                        <u-switch v-model="item.value" activeColor="#37B874"></u-switch>
                    </view>
                    <view v-else-if="item.type === 'select'" style="width: 40%;text-align: right;padding-right: 50rpx;"@click="scoringModePopUp=true" >
                        <!-- <u-select :options="['A', 'B', 'C', 'D']" :customStyle="{ width: '60%' }" v/> -->
                        <text style="margin-right: 10rpx;">{{ item.value }}</text>

                    </view>
                    <view v-else-if="item.type === 'text'" style="width: 35%;display: flex;align-items: center;">
                        <u--input type="number" v-model="item.value" placeholder="请输入"
                            :customStyle="{ width: '80%' }" />
                        <text style="margin-left: 10rpx;"><text style="color: #fff;" v-if=" item.text !== '考试时长'">分</text>{{ item.text === '考试时长' ? '分钟' : '分' }}</text>
                    </view>
                </view>
                <view v-if="item.type === 'select'"  style="position: absolute;right: 0;top: 2rpx;">
                    <u-icon name="arrow-right" size="20"></u-icon>
                </view>

            </view>
            <view style="display: flex;justify-content: space-around;margin-top: 60rpx;">
                <button type="default" hover-class="hoverClass"
                    style="color:#37B874; width:300rpx; line-height: 72rpx;background-color: #fff;font-size: 16px;border: 1px solid #37B874;border-radius: 10px;margin:0;padding: 0 8rpx;"
                    @click="() => {
                        onRecord(item)
                    }">
                    模拟记录
                    <text style="margin-left: 10rpx;background-color: #EED682;color: #A86C12;padding: 0 20rpx;border-radius: 15px;font-size: 12px;">vip1</text>    
                </button>
                <button type="default" hover-class="hoverClass"
                    style="color:#fff; width: 250rpx; line-height: 72rpx;background-color: #37B874;margin:0"
                    class="gradient-button" @click="() => { 
                        onStartExam()
                    }">进入考试</button>
            </view>
            <BotMenu :isPopup="scoringModePopUp" @close="scoringModePopUp = false" title="多选题得分模式" :showCancel="true">
                <view class="scoringModePopUpStyle">
                    <view class="flex between itemComStyle borderTopStyle" >
                        <text class="required item-center">试题类型</text>
                        <view class="flex">
                            <View v-for="item in dictType" :key="item.value" class="flex item-center">
                                <view class="flex center item-center" style="margin-left: 60rpx;":class="item.value==modeDataObj.multipleRule ? 'active' : 'noActive'"
                                    @click="modeDataObj.multipleRule=item.value">
                                    <u-icon size="40rpx" :color="item.selectStatus ? '#FFF' : '#FFF'" name="checkmark" />
                                </view>
                                <text style="margin-left: 24rpx">{{ item.text }}</text>
                            </View>
                        </view>
                    </view>
                    <view v-if="modeDataObj.multipleRule!=1">
                        <view class="flex between itemComStyle borderTopStyle item-center">
                            <text class="required">答对一项得分</text>
                            <view class="flex item-center">
                                <!-- <u-number-box  decimal-length="1" ></u-number-box> -->
                                <input class="inputStyleScore" v-model="modeDataObj.oneOptionScore" @input="(e)=>checkAmount(e,'oneOptionScore')" type="digit"/>
                                <text>分</text>
                            </view>
                        </view>
                        <view class="flex between itemComStyle borderTopStyle item-center item-center">
                            <text class="required">未全部答对最高得分</text>
                            <view class="flex item-center">
                                <!-- <u-number-box  decimal-length="1" ></u-number-box> -->
                                <input class="inputStyleScore" v-model="modeDataObj.imperfectMaxScore" @input="(e)=>checkAmount(e,'imperfectMaxScore')" type="digit"/>
                                <text>分</text>
                            </view>
                        </view>
                    </view>
                </view>
                <view class="okBtn center" @click="onSaveModeData">
                    确定
                </view>
            </BotMenu>
        </view>
    </view>

</template>

<script>
import { composePaper, getMarketExamItemType, listPractice } from '../services/QuestionBankService';
import { mapDictCodes } from '../services/ServerService';
import { getArrObjectByProperty, notificationFun } from '../utils/PrjUtils';

export default {
    data() {
        return {
            marketId: '',
            questionTypes: [
                // { type: "单选题", cnt: '', score: '' },
                // { type: "多选题", cnt: '', score: '' },
                // { type: "简答题", cnt: '', score: '' },
                // { type: "案例题", cnt: '', score: '' },
            ],
            totalScore: 0,  // 总分
            totalNum: 0,  // 总数量
            fieldArr: [
                { text: "考试时长", dataIndex: "time", type: "text", value: '' },
                { text: "及格分数", dataIndex: "passScore", type: "text", value: '' },
                { text: "答题后显示答案", dataIndex: "answerToShow", type: "switch", value: false },
                { text: "多选题得分模式", dataIndex: "scoreModel", type: "select", value: '整项得分' },
                { text: "选项乱序", dataIndex: "disruptionModel", type: "switch", recharge: true, value: false,vip:true },
                { text: "错题优先", dataIndex: "wrongFirst", recharge: true, type: "switch", value: false,vip:true },
                { text: "未做题优先", dataIndex: "nullFirst", recharge: true, type: "switch", value: false,vip:true },
            ],
            // 多选得分模式
            scoringModePopUp:false,
            dictType:[{text:"整项得分",value:1},{text:"单项得分",value:2}],
            multipleRule:1,
            oneOptionScore:"",
            imperfectMaxScore:"",
            modeDataObj:{
                multipleRule:1,
                oneOptionScore:"",
                imperfectMaxScore:"",
            }
        }
    },
    watch: {
        // 可以使用watch监听 questionTypes 的变化，确保计算总分时数据最新
        'questionTypes': {
            handler() {
                this.calculateTotalScore();
            },
            deep: true,
        },
    },
    onLoad(option) {
        this.marketId = option.marketId
        this.onMapDictCodes()
        this.onGetMarketExamItemType()
    },
    computed: {},
    methods: {
        // 查询题型数量
        onGetMarketExamItemType() {
            getMarketExamItemType({ marketId: this.marketId }).then(res => {
                // this.questionTypes = res.items
                res.forEach(item => {
                    item.cnt = ''
                    item.score = ''
                })
                if(!res.some(item=>item.type=="0301")){
                    this.fieldArr=[...this.fieldArr].filter(item=>item.text!="多选题得分模式")
                }
                this.questionTypes = res
            })
        },
        // 计算总分
        calculateTotalScore() {
            this.questionTypes.forEach(item => {
                if (item.cnt > item.itemNum) {
                    notificationFun('题目数量不能大于题目总数')
                    item.cnt = 0
                    return
                }
            })
            this.totalScore = this.questionTypes.reduce((total, item) => {
                return Number(total) + Number(item.cnt) * Number(item.score);
            }, 0);
            this.totalNum = this.questionTypes.reduce((total, item) => {
                return Number(total) + Number(item.cnt);
            }, 0);
        },

        onChangeDict(val, dict) {
            if (dict) {
                return getArrObjectByProperty(dict, 'value', val)?.label || ''
            }
        },
        onMapDictCodes() {
            mapDictCodes('allQuestionType').then(res => {
                this.mapDictCodesData = res
            })
        },
        onStartExam() {
            // if (this.totalScore === 100) {
                let obj = {}
                console.log(this.fieldArr);
                console.log(this.questionTypes,'208');
                this.questionTypes.forEach(item => {
                  item.cnt = item.cnt || 0
                  item.score = item.score || 0
                })
                this.fieldArr.forEach(item => {
                    obj[item.dataIndex] = item.value
                })
                obj.itemTypes = this.questionTypes
                obj.scoreModel = ''
                obj.score = this.totalScore
                // 类型
                obj.multipleRule=this.multipleRule
                if(this.multipleRule!=1){
                    let duoxuanItem=this.questionTypes.find(item=>item.type=="0301")
                    if(!duoxuanItem.score){
                        return notificationFun("请填写多选题分值")
                    }
                    else if(Number(duoxuanItem.score)<this.oneOptionScore){
                        return notificationFun("答对一项得分分值需要小于等于多选题分值")
                    }
                    else if(Number(duoxuanItem.score)<this.imperfectMaxScore){
                        return notificationFun("未全部答对最高得分分值需要小于等于多选题分值")
                    }
                    obj.oneOptionScore= this.oneOptionScore,
                    obj.imperfectMaxScore=this.imperfectMaxScore
                }
                console.log(obj, 'obj');
                if(!obj.time){
                    notificationFun('请填写考试时长')
                    return 
                }
                if(!obj.passScore){
                    notificationFun('请填写及格分数')
                    return 
                }
                composePaper({ marketId: this.marketId, json: obj }).then(res => {
                    uni.navigateTo({
                        url: `/pages/practiceTesting/selfTestingPage?bhCheckUuid=${res.bhCheckUuid}&title=${res.name}&testTime=${res.testTime}&bhCheckId=${res.bhCheckId}&isPaper=true&isExhibition=${obj.answerToShow}`
                    })
                })
            // } else {
            //     notificationFun('总分必须为100分')
            // }

        },
        onRecord(item) {
			uni.navigateTo({
				url: '/pages/practiceTesting/recordPage?isPaper=true&marketId=' + this.marketId 
			})
		},
        onSaveModeData(){
            const { multipleRule,oneOptionScore,imperfectMaxScore,}=this.modeDataObj
            if(multipleRule==2){
                let duoxuanItem=this.questionTypes.find(item=>item.type=="0301")
                if(!oneOptionScore){
                    return notificationFun("请填写答对一项得分分值")
                }
                else if(!imperfectMaxScore){
                    return notificationFun("请填写未全部答对最高得分分值")
                }
                else if(!duoxuanItem.score){
                    return notificationFun("请填写多选题分值")
                }
                else if(Number(duoxuanItem.score)<oneOptionScore){
                    return notificationFun("答对一项得分分值需要小于等于多选题分值")
                }
                else if(Number(duoxuanItem.score)<imperfectMaxScore){
                    return notificationFun("未全部答对最高得分分值需要小于等于多选题分值")
                }
            }
            this.multipleRule=multipleRule
            this.oneOptionScore=oneOptionScore
            this.imperfectMaxScore=imperfectMaxScore
            this.fieldArr=[...this.fieldArr].map(item=>{
                if(item.text=="多选题得分模式"){
                    return {...item,value:multipleRule==1?"整项得分":"单项得分"}
                }
                else{
                    return item
                }
            })
            this.scoringModePopUp=false
        },
        checkAmount(e,type) {
            // 部分情况 , 事件参数e会有一定区别, 这里只需要 e.detail.value 是输入的那个字符串即可
            let num = e.detail.value.match(/^\d*(\.?\d{0,1})/g)[0] || null;
            console.log(num,"---255")
            this.$nextTick(() => {
                this.modeDataObj={...this.modeDataObj,[type]:num};
            });
        },

    },
    onShow() {

    },

}
</script>

<style lang="scss">
page{
    background-color: #fff !important;
}
.question-type {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;

    text {
        width: 50%;
    }
}

.hoverClass {
    opacity: 0.5;
}
.scoringModePopUpStyle{
    .itemComStyle{
        padding: 40rpx;
    }
    .borderTopStyle{
        border-top: 1rpx solid #F2F2F2;
    }
    .active {
            background: rgba(55, 184, 116, 1);
            border-radius: 50%;
            /* padding: 4rpx; */
            width: 40rpx;
            height: 40rpx;
            border: 1px solid rgba(55, 184, 116, 1);
        }
    
    .noActive {
        background: #FFF;
        border-radius: 50%;
        /* padding: 2px; */
        width: 40rpx;
        height: 40rpx;
        border: 1px solid #F2F2F2;
    }
    .inputStyleScore{
        width:180rpx ;
        height: 80rpx;
        margin-right: 20rpx;
        border-radius: 24rpx;
        background-color: #F9F9F9;
        padding-left: 20rpx;
    }
}
.okBtn {
    padding: 32rpx;
    border-top: 1px solid #EEEEEE;
}
.required:before {
    display: inline-block;
    margin-right: 8rpx;
    content: "*";
    line-height: 1;
    font-size: 32rpx;
    color: #f04134;
}

</style>